package com.learn.netty_learn;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

public class P2_02_HelloServer {

    public static void main(String[] args) {
        // 1. 启动器，负责组装netty组件，启动服务器
        new ServerBootstrap()
            // 2. 添加处理器组，EventLoopGroup是处理所有事件的线程池
            .group(new NioEventLoopGroup())
            // 3. 选择服务器的ServerSocketChannel的实现
            .channel(NioServerSocketChannel.class)
            // 4. boss负责处理连接，worker（child）负责处理读写，决定了worker能执行那些操作（handler）
            .childHandler(
                new ChannelInitializer<NioSocketChannel>() {
                    // 5. channel注册后会执行initChannel，添加handler
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringDecoder()); //将ByteBuf转换为字符串
                        // 6. 添加handler，处理读事件 
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { // 自定义handler 
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                // 打印字符串
                                System.out.println(msg);
                            }
                        });
                    }
                }
            )
            // 7. 绑定端口
            .bind(8080);
    }
}